/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package visao.cliente;

import controle.modelo.ControleCliente;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Cliente;

/**
 *
 * @author luiz.filho
 */
public class AddClientesForm extends javax.swing.JFrame
{

    /**
     * Creates new form PesquisarClientesForm
     */
    ControleCliente controleCliente;
    List<Cliente> clientesFiltrados;
    Cliente cliente;

    public AddClientesForm()
    {
        controleCliente = new ControleCliente();
        initComponents();
    }

    public Cliente getCliente()
    {
        return cliente;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        nomeDoClienteLabel = new javax.swing.JLabel();
        nomeDoClienteInput = new javax.swing.JTextField();
        pesquisarButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonAddCliente = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        nomeDoClienteLabel.setText("Nome do Cliente");

        pesquisarButton.setText("Pesquisar");
        pesquisarButton.setToolTipText("");
        pesquisarButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                pesquisarButtonActionPerformed(evt);
            }
        });
        pesquisarButton.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
                pesquisarButtonKeyPressed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String []
            {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButtonAddCliente.setText("Adicionar");
        jButtonAddCliente.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonAddClienteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(nomeDoClienteLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nomeDoClienteInput, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(pesquisarButton)
                .addGap(18, 18, 18)
                .addComponent(jButtonAddCliente)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nomeDoClienteLabel)
                    .addComponent(nomeDoClienteInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pesquisarButton)
                    .addComponent(jButtonAddCliente))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private void atualizaTabela()
    {
        String[] columnNames =
        {
            "Id","Nome", "Endereço", "Telefone", "Email", "Editar"
        };
        Object[][] data = new Object[clientesFiltrados.size()][5];
        for (int i = 0; i < clientesFiltrados.size(); i++)
        {
            data[i][0] = clientesFiltrados.get(i).getIdCliente().toString();
            data[i][1] = clientesFiltrados.get(i).getNome();
            data[i][2] = clientesFiltrados.get(i).getEndereco();
            data[i][3] = clientesFiltrados.get(i).getTelefone();
            data[i][4] = clientesFiltrados.get(i).getEmail();
           
        }
        jTable1.setModel(new DefaultTableModel(data, columnNames));
    }

    private void pesquisarButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_pesquisarButtonActionPerformed
    {//GEN-HEADEREND:event_pesquisarButtonActionPerformed

        clientesFiltrados = controleCliente.getClienteNomeLike(nomeDoClienteInput.getText());
        atualizaTabela();

    }//GEN-LAST:event_pesquisarButtonActionPerformed

    private void pesquisarButtonKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_pesquisarButtonKeyPressed
    {//GEN-HEADEREND:event_pesquisarButtonKeyPressed
        if (evt.equals(KeyEvent.VK_ENTER))
        {
            clientesFiltrados = controleCliente.getClienteNomeLike(nomeDoClienteInput.getText());
            atualizaTabela();
        }

    }//GEN-LAST:event_pesquisarButtonKeyPressed

    private void jButtonAddClienteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonAddClienteActionPerformed
    {//GEN-HEADEREND:event_jButtonAddClienteActionPerformed
        if (jTable1.getSelectedRow() == -1)
        {
            JOptionPane.showMessageDialog(null, "Favor selecionar uma linha!");
        }
        else
        {
            int selectedRowIndex = jTable1.getSelectedRow();
            int desiredColumn = 0;
            String selectedId = (String) jTable1.getModel().getValueAt(selectedRowIndex, desiredColumn);
            this.cliente = controleCliente.getClienteById(Integer.valueOf(selectedId));
            dispose();
        }
    }//GEN-LAST:event_jButtonAddClienteActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(AddClientesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(AddClientesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(AddClientesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(AddClientesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddCliente;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField nomeDoClienteInput;
    private javax.swing.JLabel nomeDoClienteLabel;
    private javax.swing.JButton pesquisarButton;
    // End of variables declaration//GEN-END:variables
}
